package com.lw.common.utils

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.*

/**
 * 保存文件到本地
 */
object SaveDeviceMessageInfo {
    var fileName = "id.txt" //保存设备ID
    var rateName = "updateTrackLog.txt" //保存设备收费标准
    var PATH_SAVE_LOG = (Environment.getExternalStorageDirectory().absolutePath
            + File.separator + "errorlog/")

    @Throws(IOException::class)
    fun writeLog(context: Context, content: String) {
        val absolutePath = context.getFileStreamPath(rateName).path
        val file = File(absolutePath)
        val strContent = """
            $content
            
            """.trimIndent()
        //        if (file.exists()) {
//            file.delete();
//        }
        val outputStream = RandomAccessFile(file, "rwd")
        outputStream.write(strContent.toByteArray())
        outputStream.close()
    }

    @Throws(IOException::class)
    fun readLog(context: Context): String {
        val absolutePath = context.getFileStreamPath(rateName).path
        val file = File(absolutePath)
        val stringBuilder = StringBuilder()
        val inputStream: InputStream = FileInputStream(file)
        val inputReader = InputStreamReader(inputStream)
        val buffReader = BufferedReader(inputReader)
        var line: String
        while (buffReader.readLine().also { line = it } != null) {
            stringBuilder.append(line + "\r\n")
        }
        inputStream.close()
        return stringBuilder.toString()
    }

    /**
     * 字符串写入本地txt
     *
     * @param strContent 文件内容
     * @return 写入结果
     */
    fun writeTxtToFile(strContent: String): Boolean {
        var isSavaFile = false
        makeFilePath(PATH_SAVE_LOG, rateName)
        val strFilePath = PATH_SAVE_LOG + rateName
        val strContent1 = strContent + "\r\n"
        try {
            val file = File(strFilePath)
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:$strFilePath")
                file.parentFile!!.mkdirs()
                file.createNewFile()
            }
            val raf = RandomAccessFile(file, "rwd")
            raf.seek(file.length())
            raf.write(strContent1.toByteArray())
            raf.close()
            isSavaFile = true
        } catch (e: Exception) {
            isSavaFile = false
            Log.e("TestFile", "Error on write File:$e")
        }
        return isSavaFile
    }

    /**
     * 生成文件
     *
     * @param filePath 文件地址
     * @param fileName 文件名
     */
    private fun makeFilePath(filePath: String, fileName: String) {
        var file: File? = null
        makeRootDirectory(filePath)
        try {
            file = File(filePath + fileName)
            if (!file.exists()) {
                file.createNewFile()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 生成文件夹
     */
    fun makeRootDirectory(filePath: String) {
        var file: File?
        try {
            file = File(filePath)
            if (!file.exists()) {
                file.mkdir()
            }
        } catch (e: Exception) {
            Log.i("error:", e.toString() + "")
        }
    }

    /**
     * 读取本地文件
     */
    fun readDeviceId(): String {
        val path = "+ fileName"
        val stringBuilder = StringBuilder()
        val file = File(path)
        if (!file.exists()) {
            return ""
        }
        if (file.isDirectory) {
            Log.e("TestFile", "The File doesn't not exist.")
            return ""
        } else {
            try {
                val inputStream: InputStream = FileInputStream(file)
                val inputReader = InputStreamReader(inputStream)
                val buffReader = BufferedReader(inputReader)
                var line: String?
                while (buffReader.readLine().also { line = it } != null) {
                    stringBuilder.append(line)
                }
                inputStream.close()
            } catch (e: FileNotFoundException) {
                Log.e("TestFile", "The File doesn't not exist.")
                return ""
            } catch (e: IOException) {
                Log.e("TestFile", e.message!!)
                return ""
            }
        }
        return "Base64Util.decode(stringBuilder.toString())" //对读到的设备ID解密
    }

    /**
     * 读取本地文件
     */
    fun readRate(): String {
        val path = PATH_SAVE_LOG + rateName
        val stringBuilder = StringBuilder()
        val file = File(path)
        if (!file.exists()) {
            return ""
        }
        if (file.isDirectory) {
            Log.e("TestFile", "The File doesn't not exist.")
            return ""
        } else {
            try {
                val inputStream: InputStream = FileInputStream(file)
                val inputReader = InputStreamReader(inputStream)
                val buffReader = BufferedReader(inputReader)
                var line: String
                while (buffReader.readLine().also { line = it } != null) {
                    stringBuilder.append(line + "\r\n")
                }
                inputStream.close()
            } catch (e: FileNotFoundException) {
                Log.e("TestFile", "The File doesn't not exist.")
                return ""
            } catch (e: IOException) {
                Log.e("TestFile", e.message!!)
                return ""
            }
        }
        return stringBuilder.toString() //对读到的设备ID解密
    }

    /**
     * 删除单个文件
     *
     * @return 单个文件删除成功返回true，否则返回false
     */
    fun deleteFile(): Boolean {
        val path = PATH_SAVE_LOG + rateName
        val file = File(path)
        return if (file.isFile || file.exists()) {
            file.delete()
        } else {
            true
        }
    }
}